package com.weiyi.mashangzhu.Roomer.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.IsPhoneNum;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.Md5Utils;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.easemob.db.ChatDao;
import com.weiyi.mashangzhu.listener.CallBackListener;
import com.weiyi.mashangzhu.wxapi.WXEntryActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.login_phone)
    EditText loginPhone;
    @BindView(R.id.login_pwd)
    EditText loginPwd;
    @BindView(R.id.login_register)
    TextView loginRegister;
    @BindView(R.id.login_forget_pwd)
    TextView loginForgetPwd;
    @BindView(R.id.login_submit)
    Button loginSubmit;
    @BindView(R.id.login_wx)
    TextView loginWx;
    String string = "";
    private IWXAPI msgApi;
    String info="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        MyApp.getInstance().addActivity(this);
        loginPhone.setText(SPUtils.get(LoginActivity.this,"uAccount","")+"");
        loginPwd.setText(SPUtils.get(LoginActivity.this,"uPassword","")+"");
        Intent intent = getIntent();
        string = intent.getStringExtra("string");
        info=intent.getStringExtra("info");
        SPUtils.put(this,"getOpenId","");
        if (info!=null){
            if (info.equals("logout")){
//                MyApp.getInstance().exit_login();
            }
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        UiUtil.startActivity(this,MainActivity_R.class);
    }

    @OnClick({R.id.login_register, R.id.login_forget_pwd, R.id.login_submit, R.id.login_wx, R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                UiUtil.startActivity(this,MainActivity_R.class);
                finish();
                break;
            case R.id.login_register:
                UiUtil.startActivity(this, RegisterActivity.class);
                break;
            case R.id.login_forget_pwd:
                //忘记密码
                Intent intent=new Intent(this,NewPwdActivity.class);
                intent.putExtra("info","login");
                startActivity(intent);
                break;
            case R.id.login_submit:
                if ((loginPhone.getText() + "").equals("")) {
                    T.showShort(this, "手机号不能为空");
                } else {
                    if (IsPhoneNum.isMobileNO(loginPhone.getText() + "") == false) {
                        T.showShort(this, "请输入合法手机号");
                    } else {
                        if ((loginPwd.getText() + "").equals("") ) {
                            T.showShort(this, "密码不能为空");
                        } else {
                            if (!(SPUtils.get(this,"cid","")+"").equals("")) {
                                final String uAccount = loginPhone.getText() + "";
                                final String uPassword = loginPwd.getText() + "";
                                SPUtils.put(LoginActivity.this,"uAccount",uAccount);
                                SPUtils.put(LoginActivity.this,"uPassword",uPassword);
                                LoadingDialog.show(LoginActivity.this);

                                OkHttpUtils.get().addParams("uAccount", uAccount)
                                        .addParams("uPassword", uPassword)
                                        .addParams("uCid", SPUtils.get(this,"cid","")+"")
                                        .url(API.BaseApi_R + API.Login_Api)
                                        .build().execute(new StringCallback() {
                                    @Override
                                    public void onError(Request request, Exception e) {
                                        LoadingDialog.dismiss(LoginActivity.this);
                                        T.showShort(LoginActivity.this,"数据获取失败，请稍后再试");
                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        Log.e("seeeeeeeeeeeee","==="+response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String status = jsonObject.getInt("status") + "";
                                            String msg = jsonObject.getString("msg");
                                            if (status.equals("0")) {
                                                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                                                String token = jsonObject1.getString("token");
                                                String uNickname = jsonObject1.getString("uNickname");
                                                String uHead = jsonObject1.getString("uHead");
                                                // APP登录成功后，接着登录环信
                                                if (token != null) {
                                                    String[] split = token.split("@");
                                                    if (split.length > 1) {
                                                        String userAccount = split[1];
                                                        if (userAccount != null) {
                                                            saveNickAndAvatar(userAccount, uNickname, uHead);
                                                            logoutEaseMob(userAccount, Md5Utils.getEncryption(uPassword), msg, token);

                                                        }
                                                    }
                                                }
                                            } else {
                                                LoadingDialog.dismiss(LoginActivity.this);
                                                T.showShort(LoginActivity.this, msg);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            } else {
                                T.showShort(LoginActivity.this, "推送初始化失败,请稍后再试");
                            }
                        }


                    }
                }


                break;
            case R.id.login_wx:
                msgApi = WXAPIFactory.createWXAPI(this, null);
                msgApi.registerApp("wx29a520b1867fe3a2");
                if (!MyApp.mWxApi.isWXAppInstalled()) {
                    T.showShort(this, "您还未安装微信客户端");
                    return;
                }
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_base";
                req.state = "wechat_sdk_demo";
                msgApi.sendReq(req);
                break;
        }
    }

    private void saveNickAndAvatar(String userAccount, String uNickname, String uHead) {
        ChatDao chatDao = new ChatDao(this);
        if (!chatDao.isExist(userAccount)) {
            chatDao.add(userAccount, uNickname, uHead);
        } else {
            chatDao.update(userAccount, uNickname, uHead);
        }
    }
    private void logoutEaseMob(final String uAccount, final String uPassword, final String msg, final String data) {
        EMClient.getInstance().logout(true, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                SPUtils.put(LoginActivity.this, "token", "");
                SPUtils.put(LoginActivity.this, "isLogin", "0");
                loginEaseMob(uAccount, uPassword, msg, data);
            }

            @Override
            public void onMainError(int code, String message) {
                LoadingDialog.dismiss(LoginActivity.this);
                T.showShort(LoginActivity.this, "error:" + code + " " + message);
            }
        });
    }
    private void loginEaseMob(String uAccount, String uPassword, final String msg, final String data) {

        EMClient.getInstance().login(uAccount, uPassword, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                LoadingDialog.dismiss(LoginActivity.this);
                loginSuccess(msg, data);
            }
            @Override
            public void onMainError(int code, String message) {
                LoadingDialog.dismiss(LoginActivity.this);
                T.showShort(LoginActivity.this, "error:" + code + " " + message);
            }
        });
    }

    private void loginSuccess(String msg, String data) {
        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();

        //登录成功
        T.showShort(LoginActivity.this, msg);
        //存储token
        SPUtils.put(LoginActivity.this, "token", data);
        SPUtils.put(LoginActivity.this, "isLogin", "1");
//                if (string.equals("变身房东")) {
//                    UiUtil.startActivity(LoginActivity.this, MainActivity_L.class);
//                } else {
        UiUtil.startActivity(LoginActivity.this, MainActivity_R.class);
//                }
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        boolean wxLabel = (boolean) SPUtils.get(LoginActivity.this, "wxLabel", false);
//        if (wxLabel) {
//            String wxToken = (String) SPUtils.get(LoginActivity.this, "wxToken", null);
//            if (wxToken != null) {
//                login(wxToken);
//            }
//        }
//    }


}
